import React, { useState, useMemo, useEffect, useRef } from 'react';
import { Card, Typography, Tag, Button, Input, Divider, Upload, message, Spin } from 'antd';
import { SaveOutlined, CloseOutlined, UploadOutlined, ReloadOutlined, RobotOutlined, InboxOutlined, BarChartOutlined, SendOutlined, SearchOutlined } from '@ant-design/icons';
import { Customer } from '../types';
import { type Strategy } from '../types/strategies';
import { ThinkingProcess } from './ThinkingProcess';

import { streamApiService } from '../lib/streamApi';
import { strategyApi, updateCustomerOverrideStrategy } from '../lib/api';
import { uploadFile, validateFileType, validateFileSize, getFileTypeErrorMessage, getFileSizeErrorMessage } from '../lib/uploadApi';
import { formatFileSize } from '../utils/numberFormat';
import SmartSegmentedMessageRenderer from './SmartSegmentedMessageRenderer';
import { formatTimestamp } from '../utils/timeUtils';

const { Title, Text } = Typography;
const { Dragger } = Upload;

// 全局策略缓存，避免切换客户时重复请求
let globalStrategyCache: any[] = [];
let isStrategyLoaded = false;
let globalStrategyPromise: Promise<any> | null = null;

interface AssetAllocationPageProps {
  currentCustomer: Customer;
  onSendToUser?: (content: string) => void;
  clearUploadedFiles?: boolean;
  deepThinkingEnabled?: boolean;
  thinkingCallbacks?: any; // 思考过程回调
}

// 上传文件类型
interface UploadedFile {
  uid: string;
  name: string;
  size: number;
  type: string;
  url?: string;
}

// 策略卡片组件
const StrategyCard: React.FC<{
  strategy: Strategy;
  showSaveButton?: boolean;
  onSave?: () => void;
  showResetButton?: boolean;
  onReset?: () => void;
  isChanged?: boolean;
  isSystemMatched?: boolean;
  isOverrideStrategy?: boolean;
}> = ({ strategy, showSaveButton = false, onSave, showResetButton = false, onReset, isChanged = false, isSystemMatched = false, isOverrideStrategy = false }) => {
  return (
    <div className="strategy-card-container">
      <div className="flex items-start gap-3">
        <div className="flex-shrink-0 mt-1">
          <BarChartOutlined className="text-lg text-blue-500" />
        </div>
        <div className="flex-1">
          <div className="flex items-center justify-between mb-2">
            <div className="strategy-card-title">{strategy.strategy_name}</div>
            {isSystemMatched && !isOverrideStrategy && (
              <Tag className="strategy-recommended-tag">
                推荐
              </Tag>
            )}
          </div>
          <div className="strategy-card-description">
            {strategy.strategy_detail.description}
          </div>
          {/* 显示资产配置信息 */}
          <div className="strategy-allocation-info">
            <div className="allocation-grid">
              <div className="allocation-item">
                <span className="allocation-label">货币类</span>
                <span className="allocation-value">
                  {Array.isArray(strategy.strategy_detail.coreAllocation?.currency)
                    ? strategy.strategy_detail.coreAllocation.currency.join('-')
                    : strategy.strategy_detail.coreAllocation?.currency || ''}%
                </span>
              </div>
              <div className="allocation-item">
                <span className="allocation-label">固收类</span>
                <span className="allocation-value">
                  {Array.isArray(strategy.strategy_detail.coreAllocation?.fixedIncome)
                    ? strategy.strategy_detail.coreAllocation.fixedIncome.join('-')
                    : strategy.strategy_detail.coreAllocation?.fixedIncome || ''}%
                </span>
              </div>
              <div className="allocation-item">
                <span className="allocation-label">权益类</span>
                <span className="allocation-value">
                  {Array.isArray(strategy.strategy_detail.coreAllocation?.equity)
                    ? strategy.strategy_detail.coreAllocation.equity.join('-')
                    : strategy.strategy_detail.coreAllocation?.equity || ''}%
                </span>
              </div>
              <div className="allocation-item">
                <span className="allocation-label">另类</span>
                <span className="allocation-value">
                  {Array.isArray(strategy.strategy_detail.coreAllocation?.alternative)
                    ? strategy.strategy_detail.coreAllocation.alternative.join('-')
                    : strategy.strategy_detail.coreAllocation?.alternative || ''}%
                </span>
              </div>
              {/* 全球配置策略显示QDII配置 */}
              {strategy.strategy_category === '全球配置策略' && strategy.strategy_detail.coreAllocation?.qdii && (
                <div className="allocation-item">
                  <span className="allocation-label">QDII</span>
                  <span className="allocation-value">
                    {Array.isArray(strategy.strategy_detail.coreAllocation.qdii)
                      ? strategy.strategy_detail.coreAllocation.qdii.join('-')
                      : strategy.strategy_detail.coreAllocation.qdii || ''}%
                  </span>
                </div>
              )}
            </div>
          </div>
          {(showSaveButton || showResetButton) && (
            <div className="rounded-lg flex justify-end mt-4 pr-2">
              {showResetButton && (
                <Button
                icon={<ReloadOutlined />}
                  size="small"
                  onClick={onReset}
                  className='ml-2'
                >
                  重置
                </Button>
              )}
              {showSaveButton && isChanged && (
                <Button
                  icon={<SaveOutlined />}
                  type="primary"
                  size="small"
                  onClick={onSave}
                  className='ml-2'
                >
                  保存
                </Button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const AssetAllocationPage: React.FC<AssetAllocationPageProps> = ({ currentCustomer, onSendToUser, clearUploadedFiles, deepThinkingEnabled = true, thinkingCallbacks }) => {
  const [searchValue, setSearchValue] = useState('');
  const [userStrategies, setUserStrategies] = useState<any[]>([]);
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [showInitialContent, setShowInitialContent] = useState(true);

  // 新增：上传状态管理
  const [isUploading, setIsUploading] = useState(false);

  // 新增：流式分析相关状态
  const [streamContent, setStreamContent] = useState('');
  const [finalContent, setFinalContent] = useState('');
  const [isStreamCompleted, setIsStreamCompleted] = useState(false);
  const [showStreamAnalysis, setShowStreamAnalysis] = useState(false);

  // 新增：诊断对话相关状态
  const [diagnosisChatInput, setDiagnosisChatInput] = useState('');
  const [diagnosisChatHistory, setDiagnosisChatHistory] = useState<Array<{
    id: string;
    type: 'user' | 'ai';
    content: string;
    timestamp: string;
  }>>([]);
  const [isDiagnosisChatting, setIsDiagnosisChatting] = useState(false);

  // 新增：跟踪是否进行了重置操作
  const [hasReset, setHasReset] = useState(false);

  // 思考过程状态
  const [isThinking, setIsThinking] = useState(false);
  const [thinkingContent, setThinkingContent] = useState('');
  const [isThinkingComplete, setIsThinkingComplete] = useState(false);
  const [isWaitingForThinking, setIsWaitingForThinking] = useState(false);
  const [currentQuery, setCurrentQuery] = useState('');
  const [firstLlmBlockReceived, setFirstLlmBlockReceived] = useState(false);

  // 聊天区域滚动引用
  const chatScrollRef = useRef<HTMLDivElement>(null);

  // 新增：策略库后端数据状态
  const [strategyList, setStrategyList] = useState<any[]>([]);
  const [isStrategiesLoading, setIsStrategiesLoading] = useState(true);

  // 获取用户推荐的资产配置策略（investment_strategy）
  const recommendedStrategy = useMemo(() => {
    return strategyList.filter(strategy => strategy.id === currentCustomer.investment_strategy);
  }, [currentCustomer, strategyList]);

  // 获取用户手动选择的资产配置策略（override_investment_strategy）
  const overrideStrategy = useMemo(() => {
    if (!currentCustomer.override_investment_strategy) return [];
    return strategyList.filter(strategy => strategy.id === currentCustomer.override_investment_strategy);
  }, [currentCustomer, strategyList]);

  // 获取当前应该显示的策略（优先显示手动选择的策略）
  const currentDisplayStrategy = useMemo(() => {
    return overrideStrategy.length > 0 ? overrideStrategy : recommendedStrategy;
  }, [overrideStrategy, recommendedStrategy]);

  // 检查当前选择的策略是否与数据库中保存的状态不同
  const hasStrategyChanged = useMemo(() => {
    if (userStrategies.length === 0) return false;
    
    const selectedStrategyId = userStrategies[0]?.id;
    const currentOverrideId = currentCustomer.override_investment_strategy;
    const recommendedStrategyId = recommendedStrategy[0]?.id;
    
    // 如果进行了重置操作，总是显示保存按钮
    if (hasReset) {
      return true;
    }
    
    // 如果当前选择的是推荐策略
    if (selectedStrategyId === recommendedStrategyId) {
      // 如果数据库中还有覆盖策略，说明需要清除，显示保存按钮
      return currentOverrideId !== null;
    } else {
      // 如果当前选择的不是推荐策略，且与数据库中的覆盖策略不同，显示保存按钮
      return selectedStrategyId !== currentOverrideId;
    }
  }, [userStrategies, currentCustomer.override_investment_strategy, recommendedStrategy, hasReset]);

  // 检查是否有手动覆盖策略（数据库中的值）
  const hasOverrideStrategy = useMemo(() => {
    return currentCustomer.override_investment_strategy != null;
  }, [currentCustomer.override_investment_strategy]);

  // 检查当前用户选择的策略是否与推荐策略不同
  const shouldShowResetButton = useMemo(() => {
    if (userStrategies.length === 0 || recommendedStrategy.length === 0) return false;
    return userStrategies[0]?.id !== recommendedStrategy[0]?.id;
  }, [userStrategies, recommendedStrategy]);

  // 首次进入时自动展示当前策略（推荐策略或手动选择的策略）
  useEffect(() => {
    setUserStrategies(currentDisplayStrategy);
    setHasReset(false); // 确保首次进入时重置标记为false
  }, [currentDisplayStrategy]);

  // 获取策略列表
  const fetchStrategies = async () => {
    // 如果已有缓存，直接使用
    if (isStrategyLoaded) {
      setStrategyList([...globalStrategyCache]);
      setIsStrategiesLoading(false);
      return;
    }

    // 如果正在请求中，等待当前请求
    if (globalStrategyPromise) {
      setIsStrategiesLoading(true);
      try {
        await globalStrategyPromise;
        setStrategyList([...globalStrategyCache]);
      } catch (e) {
        setStrategyList([]);
      } finally {
        setIsStrategiesLoading(false);
      }
      return;
    }

    // 发起新请求
    setIsStrategiesLoading(true);
    globalStrategyPromise = strategyApi.getStrategies();
    
    try {
      const res = await globalStrategyPromise;
      if (res.success && res.data && Array.isArray(res.data.strategies)) {
        globalStrategyCache = res.data.strategies;
        isStrategyLoaded = true;
        setStrategyList([...globalStrategyCache]);
      } else {
        setStrategyList([]);
      }
    } catch (e) {
      setStrategyList([]);
    } finally {
      setIsStrategiesLoading(false);
      globalStrategyPromise = null;
    }
  };

  useEffect(() => {
    fetchStrategies();
  }, []);

  // 搜索策略（后端）
  const searchResults = useMemo(() => {
    if (!searchValue.trim()) return [];
    return strategyList.filter(strategy =>
      strategy.strategy_name?.toLowerCase().includes(searchValue.toLowerCase()) ||
      strategy.strategy_category?.toLowerCase().includes(searchValue.toLowerCase()) ||
      (strategy.strategy_detail && strategy.strategy_detail.description.toLowerCase().includes(searchValue.toLowerCase()))
    ).slice(0, 5);
  }, [searchValue, strategyList]);

  // 添加策略到用户策略列表（替换现有策略）
  const handleAddStrategy = (strategy: any) => {
    setUserStrategies([strategy]);
    setSearchValue('');
    setHasReset(false); // 清除重置标记，因为用户手动选择了策略
    message.success(`已选择策略：${strategy.strategy_name}`);
  };

  // 重置到推荐策略
  const handleResetToRecommended = () => {
    setUserStrategies(recommendedStrategy);
    setHasReset(true); // 标记已进行重置操作
    message.success('已重置为系统推荐策略，点击保存按钮确认更改');
  };

  // 保存策略到后端
  const handleSaveStrategy = async () => {
    if (!userStrategies[0]) return;
    try {
      const selectedStrategyId = userStrategies[0].id;
      const recommendedStrategyId = recommendedStrategy[0]?.id;
      
      // 如果选择的策略与推荐策略相同，则清除覆盖设置
      const overrideStrategyId = selectedStrategyId === recommendedStrategyId ? null : selectedStrategyId;
      
      const res = await updateCustomerOverrideStrategy(currentCustomer.name, overrideStrategyId);
      if (res.success) {
        // 更新客户数据中的override_investment_strategy
        // 注意：这里直接修改props中的对象，在实际应用中应该通过状态管理或父组件回调来更新
        currentCustomer.override_investment_strategy = overrideStrategyId;
        
        // 清除重置标记
        setHasReset(false);
        
        // 强制触发重新计算
        setUserStrategies(prev => [...prev]);
        
        if (overrideStrategyId === null) {
          message.success('已保存，使用系统推荐策略');
        } else {
          message.success('已保存手动选择的策略');
        }
      } else {
        message.error(res.message || '保存策略失败');
      }
    } catch (e) {
      message.error('保存策略出错');
    }
  };

  // 文件上传配置
  const uploadProps = {
    name: 'file',
    multiple: false, // 限制一次只能上传一个文件
    accept: '.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.jpg,.jpeg,.png,.txt,.csv,.md',
    beforeUpload: async (file: File) => {
      // 检查文件类型
      if (!validateFileType(file)) {
        message.error(getFileTypeErrorMessage());
        return false;
      }

      // 检查文件大小
      if (!validateFileSize(file, 10)) {
        message.error(getFileSizeErrorMessage(10));
        return false;
      }

      // 检查总上传文件大小
      const totalSize = uploadedFiles.reduce((sum, f) => sum + (f.size || 0), 0) + file.size;
      if (totalSize > 10 * 1024 * 1024) {
        message.error('所有已上传文件总大小不能超过10M，请删除部分文件后再上传。');
        return false;
      }

      // 设置上传状态
      setIsUploading(true);

      try {
        // 使用uploadApi上传文件
        const result = await uploadFile(file, currentCustomer?.session_id);

        // 添加到文件列表
        const newFile: UploadedFile = {
          uid: Date.now().toString(),
          name: result.filename || file.name,
          size: file.size,
          type: file.type,
          url: result.docId, // 将docId存储在url字段中
        };

        setUploadedFiles(prev => [...prev, newFile]);
        message.success({ content: `${file.name} 上传成功`, key: 'upload' });
      } catch (error) {
        console.error('Upload error:', error);
        message.error({ content: `上传失败: ${error instanceof Error ? error.message : '未知错误'}`, key: 'upload' });
      } finally {
        // 清除上传状态
        setIsUploading(false);
      }

      return false; // 阻止默认上传行为
    },
    showUploadList: false,
    disabled: isUploading, // 上传中时禁用
  };

  // 移除上传的文件
  const handleRemoveFile = (uid: string) => {
    setUploadedFiles(prev => prev.filter(file => file.uid !== uid));
    message.success('文件已移除');
  };

  // 重置功能
  const handleReset = () => {
    setUploadedFiles([]);
    setUserStrategies(recommendedStrategy);
    setSearchValue('');
    setShowInitialContent(true);
    setShowStreamAnalysis(false);
    setStreamContent('');
    setFinalContent('');
    setIsStreamCompleted(false);
    setDiagnosisChatHistory([]);
    setDiagnosisChatInput('');
    setIsDiagnosisChatting(false);
    setHasReset(false);

    // 重置思考过程状态
    setIsThinking(false);
    setThinkingContent('');
    setIsThinkingComplete(false);
    setIsWaitingForThinking(false);
    setCurrentQuery('');
    setFirstLlmBlockReceived(false);

    message.success('已重置为默认状态');
  };

  // AI智能诊断 - 新的流式实现
  const handleAIAnalysis = async () => {
    setIsAnalyzing(true);
    setStreamContent('');
    setFinalContent('');
    setIsStreamCompleted(false);
    setShowStreamAnalysis(true);
    setShowInitialContent(false);

    // 重置思考过程状态
    setIsThinking(false);
    setThinkingContent('');
    setIsThinkingComplete(false);
    setIsWaitingForThinking(true);
    setFirstLlmBlockReceived(false);

    let analysisMessage = "帮我分析下现有持仓，应该怎么调配";
    const docIds = uploadedFiles.map(file => file.url).filter((url): url is string => Boolean(url));

    if (docIds.length > 0) {
      analysisMessage = `请结合我上传的资产报告，` + analysisMessage;
    }
    setCurrentQuery(analysisMessage);
    

    // 设置思考过程回调
    const enhancedThinkingCallbacks = {
      onThinkingStart: () => {
        setIsThinking(true);
        setIsWaitingForThinking(false);
        setThinkingContent('');
        setIsThinkingComplete(false);
      },
      onThinkingChunk: (_chunk: string, accumulated: string) => {
        setThinkingContent(accumulated);
      },
      onThinkingComplete: (fullThinking: string) => {
        setThinkingContent(fullThinking);
        setIsThinkingComplete(true);
        setIsThinking(false);
      },
      onLlmStart: () => {
        setIsThinking(false);
        setIsWaitingForThinking(false);
      },
      // 合并用户传入的回调
      ...thinkingCallbacks
    };


    try {
      await streamApiService.sendMessageStream(
        analysisMessage,
        (_chunk: string, accumulated: string, phase?: 'reasoning' | 'llm') => {
          if (phase === 'llm' || !phase) {
            // 第一个LLM块到达时立即隐藏思考过程
            if (!firstLlmBlockReceived && accumulated.trim()) {
              setFirstLlmBlockReceived(true);
              setIsThinking(false);
              setIsWaitingForThinking(false);
              setThinkingContent('');
              setIsThinkingComplete(false);
            }
            setStreamContent(accumulated);
          }
        },
        (fullMessage) => {
          setIsAnalyzing(false);
          setIsStreamCompleted(true);
          setFinalContent(fullMessage.text);
          setStreamContent('');
          // 重置思考过程状态
          setIsThinking(false);
          setIsWaitingForThinking(false);
          setThinkingContent('');
          setIsThinkingComplete(false);
          setFirstLlmBlockReceived(false);
          message.success('AI诊断完成，已为您生成个性化资产配置方案');
          setTimeout(() => {
            if (chatScrollRef.current) {
              chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
            }
          }, 100);
        },
        (error: string) => {
          console.error('❌ 资产配置分析失败:', error);
          setIsAnalyzing(false);
          setIsStreamCompleted(true);
          const errorMessage = '抱歉，AI分析失败，请稍后再试。';
          setFinalContent(errorMessage);
          setStreamContent('');
          // 重置思考过程状态
          setIsThinking(false);
          setIsWaitingForThinking(false);
          setThinkingContent('');
          setIsThinkingComplete(false);
          setFirstLlmBlockReceived(false);
          message.error('获取AI分析失败: ' + error);
        },
        currentCustomer.name,
        currentCustomer?.session_id,

        docIds.length > 0 ? docIds : undefined,
        'financial_invest_folio_tool_agent',
        undefined,
        !deepThinkingEnabled,
        enhancedThinkingCallbacks

      );
    } catch (error) {
      console.error('资产配置分析异常:', error);
      setIsAnalyzing(false);
      setIsStreamCompleted(true);
      const errorMessage = '抱歉，AI分析失败，请稍后再试。';
      setFinalContent(errorMessage);
      setStreamContent('');
      // 重置思考过程状态
      setIsThinking(false);
      setIsWaitingForThinking(false);
      setThinkingContent('');
      setIsThinkingComplete(false);
      setFirstLlmBlockReceived(false);
      message.error('分析失败');
    }
  };

  // 诊断对话相关函数
  const handleDiagnosisChatSend = async () => {
    if (!diagnosisChatInput.trim() || isDiagnosisChatting) return;

    const userMessage = {
      id: Date.now().toString(),
      type: 'user' as const,
      content: diagnosisChatInput.trim(),
      timestamp: new Date().toISOString()
    };

    setDiagnosisChatHistory(prev => [...prev, userMessage]);
    setDiagnosisChatInput('');
    setIsDiagnosisChatting(true);

    // 重置思考过程状态
    setIsThinking(false);
    setThinkingContent('');
    setIsThinkingComplete(false);
    setIsWaitingForThinking(true);
    setFirstLlmBlockReceived(false);

    setTimeout(() => {
      if (chatScrollRef.current) {
        chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
      }
    }, 100);

    try {
      const contextMessage = `基于以下诊断结果回答用户问题：\n\n${finalContent || streamContent}\n\n用户问题：${userMessage.content}`;
      setCurrentQuery(userMessage.content);
      const docIds = uploadedFiles.map(file => file.url).filter((url): url is string => Boolean(url));

      // 设置思考过程回调
      const enhancedThinkingCallbacks = {
        onThinkingStart: () => {
          setIsThinking(true);
          setIsWaitingForThinking(false);
          setThinkingContent('');
          setIsThinkingComplete(false);
        },
        onThinkingChunk: (_chunk: string, accumulated: string) => {
          setThinkingContent(accumulated);
        },
        onThinkingComplete: (fullThinking: string) => {
          setThinkingContent(fullThinking);
          setIsThinkingComplete(true);
          setIsThinking(false);
        },
        onLlmStart: () => {
          setIsThinking(false);
          setIsWaitingForThinking(false);
        },
        ...thinkingCallbacks
      };

      await streamApiService.sendMessageStream(
        contextMessage,
        (_chunk: string, accumulated: string) => {
          // 第一个LLM块到达时立即隐藏思考过程
          if (!firstLlmBlockReceived && accumulated.trim()) {
            setFirstLlmBlockReceived(true);
            setIsThinking(false);
            setIsWaitingForThinking(false);
            setThinkingContent('');
            setIsThinkingComplete(false);
          }
          
          setDiagnosisChatHistory(prev => {
            const newHistory = [...prev];
            const lastIndex = newHistory.length - 1;
            if (newHistory[lastIndex]?.type === 'ai') {
              newHistory[lastIndex] = {
                ...newHistory[lastIndex],
                content: accumulated
              };
            } else {
              newHistory.push({
                id: Date.now().toString() + '_ai',
                type: 'ai',
                content: accumulated,
                timestamp: new Date().toISOString()
              });
            }
            return newHistory;
          });
          setTimeout(() => {
            if (chatScrollRef.current) {
              chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
            }
          }, 100);
        },
        () => {
          setIsDiagnosisChatting(false);
          // 重置思考过程状态
          setIsThinking(false);
          setIsWaitingForThinking(false);
          setThinkingContent('');
          setIsThinkingComplete(false);
          setFirstLlmBlockReceived(false);
          setTimeout(() => {
            if (chatScrollRef.current) {
              chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;
            }
          }, 100);
        },
        (error: string) => {
          console.error('❌ 诊断对话失败:', error);
          setIsDiagnosisChatting(false);
          // 重置思考过程状态
          setIsThinking(false);
          setIsWaitingForThinking(false);
          setThinkingContent('');
          setIsThinkingComplete(false);
          setFirstLlmBlockReceived(false);
          const errorMessage = {
            id: Date.now().toString() + '_error',
            type: 'ai' as const,
            content: '抱歉，回答失败，请稍后再试。',
            timestamp: new Date().toISOString()
          };
          setDiagnosisChatHistory(prev => [...prev, errorMessage]);
          message.error('获取AI回答失败: ' + error);
        },
        currentCustomer.name,
        currentCustomer?.session_id,

        docIds.length > 0 ? docIds : undefined,
        'financial_invest_folio_tool_agent',
        undefined,
        !deepThinkingEnabled,
        enhancedThinkingCallbacks

      );
    } catch (error) {
      console.error('诊断对话异常:', error);
      setIsDiagnosisChatting(false);
      // 重置思考过程状态
      setIsThinking(false);
      setIsWaitingForThinking(false);
      setThinkingContent('');
      setIsThinkingComplete(false);
      setFirstLlmBlockReceived(false);
      message.error('对话失败');
    }
  };

  const handleDiagnosisChatClear = () => {
    setDiagnosisChatHistory([]);
    message.success('对话记录已清空');
  };

  // 复制分段内容
  const handleCopySegment = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      message.success('已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败');
    }
  };

  // 发送分段内容
  const handleSendSegment = (content: string) => {
    if (onSendToUser) {
      onSendToUser(content);
      message.success('已发送到聊天');
    }
  };

  // 渲染流式分析内容 - 使用SmartSegmentedMessageRenderer
  const renderStreamAnalysisContent = () => {
    if (isAnalyzing && !streamContent) {
      return (
        <div className="text-center py-6">
          <Text type="secondary" className="text-sm">等待AI分析响应...</Text>
        </div>
      );
    }

    if (isAnalyzing && streamContent) {
      // 流式渲染 - 统一使用SmartSegmentedMessageRenderer
      return (
          <SmartSegmentedMessageRenderer
            content={streamContent}
            itemId="stream-analysis"
            onSendSegment={handleSendSegment}
            onCopySegment={handleCopySegment}
            className="w-full h-full"
          />
      );
    }

    if (isStreamCompleted && finalContent) {
      // 最终渲染 - 统一使用SmartSegmentedMessageRenderer
      return (
        <SmartSegmentedMessageRenderer
          content={finalContent}
          itemId="final-analysis"
          onSendSegment={handleSendSegment}
          onCopySegment={handleCopySegment}
        />
      );
    }

    return (
      <div className="text-center py-4">
        <Text type="secondary" className="text-sm">暂无分析内容</Text>
      </div>
    );
  };

  // 外部控制清空上传文件
  useEffect(() => {
    if (clearUploadedFiles) {
      setUploadedFiles([]);
    }
  }, [clearUploadedFiles]);

  return (
    <div className="h-full flex flex-col">
      {/* 可滚动内容区域 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {showInitialContent && !showStreamAnalysis ? (
          // 原始初始内容
          <>
            {/* 当前客户画像总结 */}
            <div className="mb-4">
              <Text strong className="text-base text-gray-800 mb-3 block">当前客户画像总结</Text>
              <Card size="small">
                {(() => {
                  try {
                    const aiSummary = currentCustomer.ai_summary ? JSON.parse(currentCustomer.ai_summary) : null;
                    if (!aiSummary) {
                      return (
                        <Text className="text-sm text-gray-500">暂无客户画像数据</Text>
                      );
                    }

                    return (
                      <div className="space-y-3">
                        {aiSummary['个性特征'] && (
                          <div>
                            <Text strong className="text-sm text-gray-700 block mb-1">个性特征</Text>
                            <Text className="text-sm text-gray-600">{aiSummary['个性特征']}</Text>
                          </div>
                        )}

                        {aiSummary['投资风格'] && (
                          <div>
                            <Text strong className="text-sm text-gray-700 block mb-1">投资风格</Text>
                            <Text className="text-sm text-gray-600">{aiSummary['投资风格']}</Text>
                          </div>
                        )}

                        {aiSummary['关键特质'] && Array.isArray(aiSummary['关键特质']) && (
                          <div>
                            <Text strong className="text-sm text-gray-700 block mb-1">关键特质</Text>
                            <div className="flex flex-wrap gap-1">
                              {aiSummary['关键特质'].map((trait: string, index: number) => (
                                <Tag key={index} color="blue">{trait}</Tag>
                              ))}
                            </div>
                          </div>
                        )}

                        {aiSummary['风险承受能力'] && (
                          <div>
                            <Text strong className="text-sm text-gray-700 block mb-1">风险承受能力</Text>
                            <Text className="text-sm text-gray-600">{aiSummary['风险承受能力']}</Text>
                          </div>
                        )}
                      </div>
                    );
                  } catch (error) {
                    console.error('解析ai_summary失败:', error);
                    return (
                      <Text className="text-sm text-gray-500">客户画像数据格式错误</Text>
                    );
                  }
                })()}
              </Card></div>

            <Divider className="my-4" />

            {/* 客户投资策略 */}
            <div>
              <Title level={5} className="!mb-3">客户投资策略:</Title>
              <div className="space-y-3">
                {/* Loading状态 */}
                {isStrategiesLoading ? (
                  <div className="text-center py-8 text-gray-500 border border-gray-200 rounded-lg bg-gray-50">
                    <Spin size="large" />
                    <div className="mt-3 text-sm">正在加载投资策略...</div>
                  </div>
                ) : (
                  <>
                    {/* 用户的策略列表（包括匹配策略和手动添加的策略） */}
                    {userStrategies.map(strategy => (
                      <StrategyCard
                        key={strategy.id}
                        strategy={strategy}
                        showSaveButton={hasStrategyChanged}
                        onSave={handleSaveStrategy}
                        showResetButton={shouldShowResetButton}
                        onReset={handleResetToRecommended}
                        isChanged={hasStrategyChanged}
                        isSystemMatched={recommendedStrategy.some((s: any) => s.id === strategy.id)}
                        isOverrideStrategy={hasOverrideStrategy}
                      />
                    ))}

                    {/* 如果没有策略，显示提示 */}
                    {userStrategies.length === 0 && (
                      <div className="text-center py-4 text-gray-500 border border-gray-200 rounded-lg bg-gray-50">
                        <Text type="secondary">暂无匹配的投资策略</Text>
                        <div className="mt-2 text-xs text-gray-400">
                          请在下方搜索并选择合适的策略
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
            </div>
            {/* 搜索并选择策略 */}
            <div>
              <Title level={5} className="!mb-3">搜索并选择策略:</Title>

              <div className="asset-allocation-search">
                <Input
                  placeholder={isStrategiesLoading ? "正在加载策略库..." : "搜索策略名称或标签..."}
                  value={searchValue}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchValue(e.target.value)}
                  onPressEnter={(e: React.KeyboardEvent<HTMLInputElement>) => {
                    // 防止Enter键导致表单提交
                    e.preventDefault();
                  }}
                  className="mb-3"
                  allowClear
                  prefix={<SearchOutlined />}
                  disabled={isStrategiesLoading}
                />
              </div>

              {/* Loading状态下的提示 */}
              {isStrategiesLoading && (
                <div className="text-center py-4 text-gray-500">
                  <Spin size="small" />
                  <div className="mt-2 text-sm">正在加载策略库，请稍候...</div>
                </div>
              )}

              {/* 搜索结果 - 仅在非loading状态下显示 */}
              {!isStrategiesLoading && (
                <>
                  {searchValue.trim() && (
                    <div className="mb-3 text-xs text-gray-500">
                      搜索关键词: "{searchValue}" | 找到 {searchResults.length} 个结果
                    </div>
                  )}
                  {searchResults.length > 0 && (
                    <div className="space-y-2">
                      {searchResults.map(strategy => (
                        <div
                          key={strategy.id}
                          className="border border-gray-200 rounded-lg p-3 hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-colors"
                          onClick={() => {
                            handleAddStrategy(strategy);
                          }}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex-1">
                              <Text strong className="text-sm">{strategy.strategy_name}</Text>
                              <div className="mt-1">
                                <Tag color="blue" className="text-xs">
                                  {strategy.strategy_category}
                                </Tag>
                              </div>
                            </div>
                            <Button type="link" size="small">
                              选择
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  {searchValue.trim() && searchResults.length === 0 && (
                    <div className="text-center py-4 text-gray-500">
                      <Text type="secondary">未找到匹配的策略</Text>
                    </div>
                  )}
                </>
              )}
            </div>

            <Divider className="my-4" />

            {/* 上传文件功能 */}
            <div>
              <Title level={5} className="!mb-3">上传文件:</Title>

              <Dragger {...uploadProps} className="mb-4">
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">
                  {isUploading ? '正在上传文件...' : '上传资产报告，持仓报告等补充文件'}
                </p>
                <p className="ant-upload-hint">
                  {isUploading
                    ? '请等待上传完成'
                    : '支持 PDF、Word、Excel、PPT、图片、TXT、CSV、Markdown 格式，单个文件不超过 10MB'
                  }
                </p>
              </Dragger>

              {/* 已上传文件列表 */}
              {uploadedFiles.length > 0 && (
                <div className="space-y-2 mb-4">
                  <Text strong className="text-sm">已上传文件:</Text>
                  {uploadedFiles.map(file => (
                    <div
                      key={file.uid}
                      className="border border-gray-200 rounded-lg p-3 flex items-center justify-between"
                    >
                      <div className="flex items-center space-x-2">
                        <UploadOutlined className="text-blue-500" />
                        <div>
                          <Text className="text-sm font-medium">{file.name}</Text>
                          <div className="text-xs text-gray-500">
                            {formatFileSize(file.size)}
                          </div>
                        </div>
                      </div>
                      <Button
                        type="text"
                        size="small"
                        icon={<CloseOutlined />}
                        onClick={() => handleRemoveFile(file.uid)}
                        className="text-red-500 hover:text-red-700"
                      />
                    </div>
                  ))}
                </div>
              )}
            </div>
          </>
        ) : showStreamAnalysis && (
          // 流式分析结果内容 - 修改为固定高度布局
          <div className="h-full flex flex-col">
            {/* 返回按钮和标题 - 固定区域 */}
            <div className="flex-shrink-0 space-y-3 mb-4">
              {/* 返回按钮 */}
              <div className="flex items-center">
                <Button
                  type="text"
                  size="small"
                  onClick={() => {
                    setShowStreamAnalysis(false);
                    setShowInitialContent(true);
                    setStreamContent('');
                    setFinalContent('');
                    setIsStreamCompleted(false);
                    // 清空诊断对话历史
                    setDiagnosisChatHistory([]);
                    setDiagnosisChatInput('');
                    setIsDiagnosisChatting(false);
                    setCurrentQuery('');
                    setFirstLlmBlockReceived(false);
                  }}
                  className="text-gray-500 hover:text-gray-700 px-0"
                >
                  ← 返回资产配置
                </Button>
              </div>

              {/* 分析结果头部 */}
              <div>
                <Title level={5} className="!mb-1 text-gray-800">AI 资产配置分析结果</Title>
                <Text type="secondary" className="text-sm">为 {currentCustomer.name} 提供的个性化配置建议</Text>
              </div>
            </div>

            {/* 统一的对话区域 - 包含分析内容和用户对话 */}
            <div className="flex-1 bg-white rounded-lg border border-gray-200 flex flex-col min-h-0">
              {/* 对话内容区域 - 可滚动区域 */}
              <div className="flex-1 overflow-y-auto p-6" ref={chatScrollRef}>
                <div className="space-y-4">
                  {/* 首次AI分析的思考过程 - 显示在分析结果前面 */}
                  {(isThinking || isWaitingForThinking || thinkingContent) && 
                   diagnosisChatHistory.length === 0 && (
                    <div className="flex justify-start">
                      <ThinkingProcess
                        type="auto"
                        mode={deepThinkingEnabled ? 'mock' : 'realtime'}
                        query={currentQuery}
                        isThinking={isThinking}
                        thinkingContent={thinkingContent}
                        isThinkingComplete={isThinkingComplete}
                        isWaitingForThinking={isWaitingForThinking}
                        className=""
                      />
                    </div>
                  )}

                  {/* 分析结果作为第一条AI消息 */}
                  {(streamContent || finalContent) && (
                    <div className="flex justify-start">
                      <div className="max-w-[90%] bg-gray-100 text-gray-800 rounded-lg px-4 py-3">
                        <div className="prose prose-sm max-w-none">
                          {renderStreamAnalysisContent()}
                        </div>
                        <div className="text-xs mt-2 opacity-70 text-gray-500">
                          AI 诊断分析
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 用户对话历史 */}
                  {diagnosisChatHistory.map((msg, index) => (
                    <div key={msg.id}>
                      {/* 用户消息 */}
                      {msg.type === 'user' && (
                        <div className="flex justify-end">
                          <div className="max-w-[80%] rounded-lg px-4 py-3 bg-blue-500 text-white">
                            <div className="space-y-3">
                              {msg.content}
                            </div>
                            <div className="text-xs mt-2 opacity-70">
                              {formatTimestamp(msg.timestamp)}
                            </div>
                          </div>
                        </div>
                      )}

                      {/* AI回答 */}
                      {msg.type === 'ai' && (
                        <>
                          {/* 思考过程 - 显示在最后一条AI回答前面 */}
                          {index === diagnosisChatHistory.length - 1 && 
                           (isThinking || isWaitingForThinking || thinkingContent) && (
                            <div className="flex justify-start mb-4">
                              <ThinkingProcess
                                type="auto"
                                mode={deepThinkingEnabled ? 'mock' : 'realtime'}
                                query={currentQuery}
                                isThinking={isThinking}
                                thinkingContent={thinkingContent}
                                isThinkingComplete={isThinkingComplete}
                                isWaitingForThinking={isWaitingForThinking}
                                className=""
                              />
                            </div>
                          )}
                          
                          <div className="flex justify-start">
                            <div className="max-w-[80%] rounded-lg px-4 py-3 bg-gray-100 text-gray-800">
                              <div className="space-y-3">
                                <SmartSegmentedMessageRenderer
                                  content={msg.content}
                                  itemId={msg.id}
                                  onSendSegment={handleSendSegment}
                                  onCopySegment={handleCopySegment}
                                />
                                <div className="text-xs mt-2 opacity-70 text-gray-500">
                                  {formatTimestamp(msg.timestamp)}
                                </div>
                              </div>
                            </div>
                          </div>
                        </>
                      )}
                    </div>
                  ))}

                  {/* 用户提问后等待AI回答时的思考过程 */}
                  {isDiagnosisChatting && diagnosisChatHistory.length > 0 && 
                   diagnosisChatHistory[diagnosisChatHistory.length - 1]?.type === 'user' &&
                   (isThinking || isWaitingForThinking || thinkingContent) && (
                    <div className="flex justify-start">
                      <ThinkingProcess
                        type="auto"
                        mode={deepThinkingEnabled ? 'mock' : 'realtime'}
                        query={currentQuery}
                        isThinking={isThinking}
                        thinkingContent={thinkingContent}
                        isThinkingComplete={isThinkingComplete}
                        isWaitingForThinking={isWaitingForThinking}
                        className=""
                      />
                    </div>
                  )}
                </div>
              </div>

              {/* 输入框区域 - 分析开始后就显示 */}
              {showStreamAnalysis && (
                <div className="flex-shrink-0 border-t border-gray-100 bg-white p-4">
                  <div className="flex gap-2">
                    <Input.TextArea
                      value={diagnosisChatInput}
                      onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setDiagnosisChatInput(e.target.value)}
                      placeholder={isAnalyzing ? "AI正在分析中，请稍后提问..." : "基于诊断结果提问，如：这个配置的风险如何？"}
                      autoSize={{ minRows: 1, maxRows: 3 }}
                      onPressEnter={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
                        if (!e.shiftKey) {
                          e.preventDefault();
                          handleDiagnosisChatSend();
                        }
                      }}
                      disabled={isDiagnosisChatting || isAnalyzing}
                      className="flex-1"
                    />
                    <Button
                      type="primary"
                      icon={<SendOutlined />}
                      onClick={handleDiagnosisChatSend}
                      disabled={!diagnosisChatInput.trim() || isDiagnosisChatting || isAnalyzing}
                      loading={isDiagnosisChatting}
                      className="flex-shrink-0"
                    >
                      {isDiagnosisChatting ? '回答中...' : isAnalyzing ? '分析中...' : '发送'}
                    </Button>
                  </div>
                  <div className="mt-2 text-xs text-gray-500 flex justify-between items-center">
                    <span>Enter 发送 | Shift + Enter 换行</span>
                    {diagnosisChatHistory.length > 0 && (
                      <Button
                        type="text"
                        size="small"
                        onClick={handleDiagnosisChatClear}
                        className="text-gray-500 hover:text-gray-700 text-xs"
                      >
                        清空对话
                      </Button>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* 底部按钮区域 - 只在初始页面显示 */}
      {showInitialContent && !showStreamAnalysis && (
        <div className="flex-shrink-0 bg-white border-t border-gray-200 px-4 py-6">
          <div className="flex gap-3">
            <Button
              icon={<ReloadOutlined />}
              onClick={handleReset}
              className="flex-1"
            >
              重置
            </Button>
            <Button
              type="primary"
              icon={<RobotOutlined />}
              onClick={handleAIAnalysis}
              loading={isAnalyzing}
              className="flex-1"
            >
              {isAnalyzing ? 'AI诊断中...' : 'AI智能诊断和建议'}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default AssetAllocationPage; 